﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Halfpipe.Data.Repository;

namespace Halfpipe.Testing.Fakes
{
    public class FakeRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private IList<TEntity> _data = new List<TEntity>();
        public IList<TEntity> Data { get { return _data; } }

        public TEntity Insert(TEntity entity)
        {
            Data.Add(entity);
            return entity;
        }

        public void Delete(TEntity entity)
        {
            Data.Remove(entity);
        }

        public void DeleteAll()
        {
            Data.Clear();
        }

        public TEntity Update(TEntity entity)
        {
            // replace object in list having same id as existingEntity with existingEntity
            dynamic dentity = entity;
            int id = dentity.Id;
            var index = Data.IndexOf(FindById(id));
            Data[index] = entity;
            return entity;
        }

        private TEntity FindById(int id)
        {
            foreach (var item in Data)
            {
                dynamic entity = item;
                if (entity.Id == id)
                {
                    return item;
                }
            }
            throw new ArgumentOutOfRangeException("id", "Object with this ID not found.");
        }

        public IQueryable<TEntity> SelectAll()
        {
            return Data.AsQueryable();
        }
    }
}
